<?php
session_start();

if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}

require_once 'track_online.php';

$currentUser = $_SESSION['username'];
$groupName = $_GET['group_name'] ?? null;

// 群聊信息文件
$infoFile = __DIR__ . '/ql/info.json';

// 确保文件存在
if (!file_exists($infoFile)) {
    file_put_contents($infoFile, json_encode([]));
}

// 读取群聊信息
$groups = json_decode(file_get_contents($infoFile), true) ?: [];

// 查找当前群聊
$currentGroup = null;
$groupId = null;
foreach ($groups as $id => $group) {
    if ($group['name'] === $groupName) {
        $currentGroup = $group;
        $groupId = $id;
        break;
    }
}

// 如果群聊不存在
if (!$currentGroup || !$groupId) {
    die("群聊不存在");
}

// 检查用户权限
$isOwner = ($currentGroup['creator'] === $currentUser);
$isAdmin = in_array($currentUser, $currentGroup['admins'] ?? []);

// 群成员文件
$membersFile = __DIR__ . "/ql/$groupId/people.json";

// 确保文件存在
if (!file_exists($membersFile)) {
    file_put_contents($membersFile, json_encode([]));
}

// 读取成员列表
$members = json_decode(file_get_contents($membersFile), true) ?: [];

// 群聊禁言文件
$groupMuteFile = __DIR__ . "/ql/$groupId/jy.json";

// 确保文件存在
if (!file_exists($groupMuteFile)) {
    file_put_contents($groupMuteFile, json_encode([]));
}

// 读取群聊禁言数据
$groupMuteData = json_decode(file_get_contents($groupMuteFile), true) ?: [];

// 全局禁言文件
$globalMuteFile = __DIR__ . "/ql/jy.json";

// 确保文件存在
if (!file_exists($globalMuteFile)) {
    file_put_contents($globalMuteFile, json_encode([]));
}

// 读取全局禁言数据
$globalMuteData = json_decode(file_get_contents($globalMuteFile), true) ?: [];

// 处理表单提交
$successMessage = '';
$errorMessage = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? null;
    
    // 更新群聊信息
    if ($action === 'update_group_info') {
        $description = trim($_POST['description'] ?? '');
        $tags = trim($_POST['tags'] ?? '');
        
        // 权限检查
        if (!$isOwner && !$isAdmin) {
            $errorMessage = '只有管理员或群主才能修改群聊信息';
        } else {
            // 群主可以更新所有信息
            if ($isOwner) {
                // 处理头像上传
                if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
                    $avatarDir = __DIR__ . "/ql/$groupId";
                    if (!is_dir($avatarDir)) {
                        mkdir($avatarDir, 0777, true);
                    }
                    
                    // 获取文件扩展名
                    $ext = pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION);
                    
                    // 删除旧头像（如果存在）
                    $oldAvatar = $currentGroup['avatar'] ?? '';
                    if ($oldAvatar && file_exists(__DIR__ . "/$oldAvatar")) {
                        // 检查扩展名是否不同
                        $oldExt = pathinfo($oldAvatar, PATHINFO_EXTENSION);
                        if (strtolower($oldExt) !== strtolower($ext)) {
                            unlink(__DIR__ . "/$oldAvatar");
                        }
                    }
                    
                    // 生成新头像文件名
                    $avatarName = "avatar.$ext";
                    $avatarPath = "$avatarDir/$avatarName";
                    
                    if (move_uploaded_file($_FILES['avatar']['tmp_name'], $avatarPath)) {
                        $currentGroup['avatar'] = "ql/$groupId/$avatarName";
                    }
                }
            }
            
            // 更新群聊信息
            $currentGroup['description'] = htmlspecialchars($description);
            $currentGroup['tags'] = htmlspecialchars($tags);
            
            // 保存到文件
            $groups[$groupId] = $currentGroup;
            file_put_contents($infoFile, json_encode($groups));
            
            $successMessage = '群聊信息已更新';
        }
    }
    
    // 禁言成员
    if ($action === 'mute_member') {
        $member = trim($_POST['member'] ?? '');
        $duration = (int)($_POST['duration'] ?? 0);
        $reason = trim($_POST['reason'] ?? '违反群规');
        
        // 验证权限
        $canMute = false;
        $errorReason = '';
        
        if (!$isOwner && !$isAdmin) {
            $errorReason = '只有管理员或群主才能禁言成员';
        } else if ($member === $currentUser) {
            $errorReason = '不能禁言自己';
        } else if ($isAdmin) {
            // 管理员只能禁言普通成员
            if ($member === $currentGroup['creator']) {
                $errorReason = '管理员不能禁言群主';
            } else if (in_array($member, $currentGroup['admins'])) {
                $errorReason = '管理员不能禁言其他管理员';
            } else {
                $canMute = true;
            }
        } else {
            $canMute = true;
        }
        
        if ($canMute && $duration > 0) {
            // 计算解禁时间
            $endTime = new DateTime();
            $endTime->add(new DateInterval('PT'.$duration.'M')); // 添加分钟
            
            // 添加禁言记录到群聊禁言文件
            $groupMuteData[$member] = [
                'year' => (int)$endTime->format('Y'),
                'month' => (int)$endTime->format('n'),
                'day' => (int)$endTime->format('j'),
                'hour' => (int)$endTime->format('G'),
                'minute' => (int)$endTime->format('i'),
                'reason' => $reason,
                'muted_by' => $currentUser,
                'muted_at' => date('Y-m-d H:i:s')
            ];
            
            file_put_contents($groupMuteFile, json_encode($groupMuteData));
            
            // 添加到全局禁言文件
            if (!isset($globalMuteData[$groupId])) {
                $globalMuteData[$groupId] = [];
            }
            
            $globalMuteData[$groupId][$member] = $groupMuteData[$member];
            file_put_contents($globalMuteFile, json_encode($globalMuteData));
            
            $successMessage = "成员 {$member} 已被禁言";
        } else if ($errorReason) {
            $errorMessage = $errorReason;
        } else if ($duration <= 0) {
            $errorMessage = '请选择有效的禁言时长';
        }
    }
    
    // 解除禁言
    if ($action === 'unmute_member') {
        $member = trim($_POST['member'] ?? '');
        
        // 验证权限
        $canUnmute = false;
        $errorReason = '';
        
        if (!$isOwner && !$isAdmin) {
            $errorReason = '只有管理员或群主才能解除禁言';
        } else if ($isAdmin) {
            // 管理员只能解除自己设置的禁言
            if (isset($groupMuteData[$member]) && 
                $groupMuteData[$member]['muted_by'] === $currentUser) {
                $canUnmute = true;
            } else {
                $errorReason = '只能解除自己设置的禁言';
            }
        } else {
            $canUnmute = true;
        }
        
        if ($canUnmute && isset($groupMuteData[$member])) {
            // 从群聊禁言文件中移除
            unset($groupMuteData[$member]);
            file_put_contents($groupMuteFile, json_encode($groupMuteData));
            
            // 从全局禁言文件中移除
            if (isset($globalMuteData[$groupId][$member])) {
                unset($globalMuteData[$groupId][$member]);
                file_put_contents($globalMuteFile, json_encode($globalMuteData));
            }
            
            $successMessage = "成员 {$member} 已解除禁言";
        } else if ($errorReason) {
            $errorMessage = $errorReason;
        } else if (!isset($groupMuteData[$member])) {
            $errorMessage = '该成员未被禁言';
        }
    }
    
    // 设置管理员
    if ($action === 'set_admin') {
        $member = trim($_POST['member'] ?? '');
        
        // 验证权限
        $errorReason = '';
        
        if (!$isOwner) {
            $errorReason = '只有群主才能设置管理员';
        } else if ($member === $currentUser) {
            $errorReason = '不能将自己设置为管理员';
        } else if ($member === $currentGroup['creator']) {
            $errorReason = '不能将群主设置为管理员';
        } else if (in_array($member, $currentGroup['admins'])) {
            $errorReason = '该成员已经是管理员';
        } else if (!in_array($member, $members)) {
            $errorReason = '该成员不在群聊中';
        }
        
        if (!$errorReason) {
            // 添加管理员
            $currentGroup['admins'][] = $member;
            
            // 保存到文件
            $groups[$groupId] = $currentGroup;
            file_put_contents($infoFile, json_encode($groups));
            
            $successMessage = "成员 {$member} 已被设置为管理员";
        } else {
            $errorMessage = $errorReason;
        }
    }
    
    // 取消管理员
    if ($action === 'remove_admin') {
        $member = trim($_POST['member'] ?? '');
        
        // 验证权限
        $errorReason = '';
        
        if (!$isOwner) {
            $errorReason = '只有群主才能取消管理员';
        } else if ($member === $currentUser) {
            $errorReason = '不能取消自己的管理员权限';
        } else if (!in_array($member, $currentGroup['admins'])) {
            $errorReason = '该成员不是管理员';
        }
        
        if (!$errorReason) {
            // 移除管理员
            $adminIndex = array_search($member, $currentGroup['admins']);
            if ($adminIndex !== false) {
                array_splice($currentGroup['admins'], $adminIndex, 1);
                
                // 保存到文件
                $groups[$groupId] = $currentGroup;
                file_put_contents($infoFile, json_encode($groups));
                
                $successMessage = "成员 {$member} 的管理员权限已被取消";
            }
        } else {
            $errorMessage = $errorReason;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>群聊管理 - <?= htmlspecialchars($groupName) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
        }
        
        body {
            background-color: #f5f7fa;
            color: #333;
        }
        
        /* 顶部导航栏 */
        .navbar {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            background: #ffffff;
            padding: 12px 20px;
            display: flex;
            align-items: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            z-index: 100;
            border-bottom: 1px solid #e0e4e9;
        }
        
        .back-btn {
            background: none;
            border: none;
            color: #000;
            font-size: 20px;
            margin-right: 10px;
            cursor: pointer;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .back-btn:hover {
            background: #e4e6eb;
        }
        
        .navbar-title {
            font-size: 18px;
            font-weight: 600;
            flex-grow: 1;
            color: #333;
        }
        
        /* 主内容区 */
        .content {
            margin-top: 70px;
            padding: 20px;
            max-width: 800px;
            margin-left: auto;
            margin-right: auto;
        }
        
        /* 消息提示 */
        .message-container {
            margin-bottom: 20px;
        }
        
        .success-message {
            background: #d4edda;
            color: #155724;
            padding: 15px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            animation: fadeIn 0.5s ease;
        }
        
        .success-message i {
            margin-right: 10px;
        }
        
        .error-message {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            animation: fadeIn 0.5s ease;
        }
        
        .error-message i {
            margin-right: 10px;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        /* 群信息卡片 */
        .group-card {
            background: white;
            border-radius: 16px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            margin-bottom: 25px;
        }
        
        .group-header {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .group-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 20px;
            background: #e0e4e9;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #7f8c8d;
            font-size: 32px;
        }
        
        .group-info {
            flex-grow: 1;
        }
        
        .group-name {
            font-size: 24px;
            font-weight: bold;
            color: #222;
            margin-bottom: 5px;
            position: relative;
            display: inline-block;
        }
        
        .group-meta {
            color: #7f8c8d;
            font-size: 14px;
        }
        
        .group-meta span {
            margin-right: 15px;
        }
        
        .group-details {
            margin-top: 20px;
        }
        
        .detail-item {
            margin-bottom: 15px;
        }
        
        .detail-label {
            font-weight: 500;
            color: #7f8c8d;
            margin-bottom: 5px;
            font-size: 14px;
        }
        
        .detail-value {
            color: #495057;
            font-size: 16px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 8px;
        }
        
        .disabled {
            background: #f0f2f5;
            color: #adb5bd;
            cursor: not-allowed;
        }
        
        /* 管理卡片 */
        .management-card {
            background: white;
            border-radius: 16px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            margin-bottom: 25px;
        }
        
        .card-title {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #f0f2f5;
            color: #222;
            display: flex;
            align-items: center;
        }
        
        .card-title i {
            margin-right: 12px;
            color: #3498db;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #444;
            font-size: 15px;
        }
        
        .form-input {
            width: 100%;
            padding: 14px;
            border: 1px solid #e0e4e9;
            border-radius: 12px;
            font-size: 15px;
            transition: all 0.3s ease;
        }
        
        .form-input:focus {
            border-color: #3498db;
            outline: none;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }
        
        .form-textarea {
            min-height: 100px;
            resize: vertical;
        }
        
        .avatar-preview {
            width: 100px;
            height: 100px;
            border-radius: 12px;
            object-fit: cover;
            margin-top: 10px;
            border: 2px dashed #e0e4e9;
        }
        
        .action-btn {
            background: #3498db;
            color: white;
            border: none;
            border-radius: 12px;
            padding: 15px 25px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            margin-right: 15px;
            margin-bottom: 15px;
        }
        
        .action-btn i {
            margin-right: 10px;
        }
        
        .action-btn:hover {
            background: #2980b9;
            transform: translateY(-3px);
            box-shadow: 0 4px 10px rgba(52, 152, 219, 0.3);
        }
        
        .logout-btn {
            background: #e74c3c;
        }
        
        .logout-btn:hover {
            background: #c0392b;
            box-shadow: 0 4px 10px rgba(231, 76, 60, 0.3);
        }
        
        .delete-btn {
            background: #95a5a6;
        }
        
        .delete-btn:hover {
            background: #7f8c8d;
            box-shadow: 0 4px 10px rgba(149, 165, 166, 0.3);
        }
        
        /* 成员列表 */
        .members-list {
            max-height: 300px;
            overflow-y: auto;
            margin-bottom: 20px;
        }
        
        .member-item {
            display: flex;
            align-items: center;
            padding: 12px;
            border-bottom: 1px solid #f0f2f5;
            transition: all 0.2s ease;
        }
        
        .member-item:hover {
            background: #f8f9fa;
        }
        
        .member-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #3498db;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 16px;
            margin-right: 15px;
        }
        
        .member-info {
            flex-grow: 1;
        }
        
        .member-name {
            font-weight: 500;
        }
        
        .member-role {
            font-size: 13px;
            color: #7f8c8d;
            margin-top: 3px;
        }
        
        .role-owner {
            color: #e67e22;
        }
        
        .role-admin {
            color: #3498db;
        }
        
        .member-actions {
            display: flex;
            gap: 8px;
        }
        
        .action-icon {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f0f2f5;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .action-icon:hover {
            background: #e0e4e9;
            transform: scale(1.1);
        }
        
        .mute-status {
            font-size: 12px;
            color: #e74c3c;
            margin-top: 5px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .mute-status i {
            font-size: 14px;
        }
        
        /* 模态框 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 200;
            justify-content: center;
            align-items: center;
        }
        
        .modal.active {
            display: flex;
        }
        
        .modal-content {
            background: white;
            width: 90%;
            max-width: 500px;
            border-radius: 16px;
            padding: 25px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.2);
        }
        
        .modal-header {
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-title {
            font-size: 20px;
            font-weight: 600;
        }
        
        .close-modal {
            background: none;
            border: none;
            font-size: 22px;
            color: #777;
            cursor: pointer;
        }
        
        .modal-body {
            margin-bottom: 20px;
        }
        
        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }
        
        .modal-btn {
            padding: 12px 25px;
            border: none;
            border-radius: 10px;
            font-size: 15px;
            font-weight: 500;
            cursor: pointer;
            min-width: 100px;
        }
        
        .modal-btn.primary {
            background: #3498db;
            color: white;
        }
        
        .modal-btn.primary:hover {
            background: #2980b9;
        }
        
        .modal-btn.secondary {
            background: #ecf0f1;
            color: #333;
        }
        
        .modal-btn.secondary:hover {
            background: #d0d3d4;
        }
        
        .modal-btn.danger {
            background: #e74c3c;
            color: white;
        }
        
        .modal-btn.danger:hover {
            background: #c0392b;
        }
        
        /* 加载指示器 */
        .loading {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255,255,255,0.8);
            z-index: 300;
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }
        
        .loading.active {
            display: flex;
        }
        
        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 15px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .content {
                padding: 15px;
            }
            
            .group-header {
                flex-direction: column;
                text-align: center;
            }
            
            .group-avatar {
                margin-right: 0;
                margin-bottom: 15px;
            }
            
            .action-btn {
                width: 100%;
                margin-right: 0;
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <div class="navbar">
        <button class="back-btn" onclick="history.back()">
            <i class="fas fa-arrow-left"></i>
        </button>
        <div class="navbar-title">群聊管理 - <?= htmlspecialchars($groupName) ?></div>
    </div>
    
    <div class="content">
        <!-- 消息提示 -->
        <div class="message-container">
            <?php if ($successMessage): ?>
                <div class="success-message">
                    <i class="fas fa-check-circle"></i>
                    <?= $successMessage ?>
                </div>
            <?php endif; ?>
            
            <?php if ($errorMessage): ?>
                <div class="error-message">
                    <i class="fas fa-exclamation-triangle"></i>
                    <?= $errorMessage ?>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- 群信息卡片 -->
        <div class="group-card">
            <div class="group-header">
                <?php if ($currentGroup['avatar']): ?>
                    <img src="<?= $currentGroup['avatar'] ?>" alt="群头像" class="group-avatar">
                <?php else: ?>
                    <div class="group-avatar">
                        <?= substr($groupName, 0, 1) ?>
                    </div>
                <?php endif; ?>
                
                <div class="group-info">
                    <div class="group-name"><?= htmlspecialchars($groupName) ?></div>
                    <div class="group-meta">
                        <span><i class="fas fa-user"></i> 创建者: <?= htmlspecialchars($currentGroup['creator']) ?></span>
                        <span><i class="fas fa-clock"></i> 创建时间: <?= htmlspecialchars($currentGroup['created_at']) ?></span>
                    </div>
                </div>
            </div>
            
            <div class="group-details">
                <div class="detail-item">
                    <div class="detail-label">群介绍</div>
                    <div class="detail-value"><?= htmlspecialchars($currentGroup['description'] ?? '暂无介绍') ?></div>
                </div>
                
                <div class="detail-item">
                    <div class="detail-label">群标签</div>
                    <div class="detail-value"><?= htmlspecialchars($currentGroup['tags'] ?? '暂无标签') ?></div>
                </div>
            </div>
        </div>
        
        <!-- 管理卡片 -->
        <div class="management-card">
            <div class="card-title">
                <i class="fas fa-cog"></i> 群聊设置
            </div>
            
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="update_group_info">
                
                <div class="form-group">
                    <label class="form-label">群聊名称</label>
                    <input type="text" class="form-input disabled" value="<?= htmlspecialchars($groupName) ?>" readonly>
                    <div class="detail-value" style="background: #fff8e6; color: #e67e22; margin-top: 5px;">
                        <i class="fas fa-info-circle"></i> 群聊名称创建后不可更改
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">群介绍</label>
                    <textarea class="form-input form-textarea" name="description"><?= htmlspecialchars($currentGroup['description'] ?? '') ?></textarea>
                </div>
                
                <div class="form-group">
                    <label class="form-label">群标签</label>
                    <input type="text" class="form-input" name="tags" value="<?= htmlspecialchars($currentGroup['tags'] ?? '') ?>" placeholder="多个标签用逗号分隔">
                </div>
                
                <?php if ($isOwner): ?>
                <div class="form-group">
                    <label class="form-label">群头像</label>
                    <input type="file" name="avatar" accept="image/*">
                    <?php if ($currentGroup['avatar']): ?>
                        <img src="<?= $currentGroup['avatar'] ?>" alt="当前头像" class="avatar-preview">
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                
                <button type="submit" class="action-btn">
                    <i class="fas fa-save"></i> 保存更改
                </button>
            </form>
        </div>
        
        <!-- 成员管理卡片 -->
        <div class="management-card">
            <div class="card-title">
                <i class="fas fa-users"></i> 成员管理
            </div>
            
            <div class="members-list">
                <?php foreach ($members as $member): ?>
                    <?php
                    $isCreator = ($member === $currentGroup['creator']);
                    $isAdminMember = in_array($member, $currentGroup['admins'] ?? []);
                    $isMuted = isset($groupMuteData[$member]);
                    $canManage = ($isOwner || ($isAdmin && !$isCreator && !$isAdminMember));
                    ?>
                    
                    <div class="member-item">
                        <div class="member-avatar">
                            <?= substr($member, 0, 1) ?>
                        </div>
                        
                        <div class="member-info">
                            <div class="member-name"><?= htmlspecialchars($member) ?></div>
                            <div class="member-role">
                                <?php if ($isCreator): ?>
                                    <span class="role-owner"><i class="fas fa-crown"></i> 群主</span>
                                <?php elseif ($isAdminMember): ?>
                                    <span class="role-admin"><i class="fas fa-shield-alt"></i> 管理员</span>
                                <?php else: ?>
                                    <span>成员</span>
                                <?php endif; ?>
                            </div>
                            
                            <?php if ($isMuted): ?>
                                <?php
                                $muteInfo = $groupMuteData[$member];
                                $unmuteTime = DateTime::createFromFormat(
                                    'Y-n-j G:i', 
                                    sprintf('%d-%d-%d %d:%d', 
                                        $muteInfo['year'],
                                        $muteInfo['month'],
                                        $muteInfo['day'],
                                        $muteInfo['hour'],
                                        $muteInfo['minute']
                                    )
                                );
                                $now = new DateTime();
                                ?>
                                <div class="mute-status">
                                    <i class="fas fa-microphone-slash"></i>
                                    禁言至: <?= $unmuteTime->format('Y-m-d H:i') ?>
                                    <?php if ($now > $unmuteTime): ?>
                                        <span style="color:#27ae60">(已过期)</span>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <?php if ($canManage || ($isOwner && $isAdminMember && $member !== $currentUser)): ?>
                            <div class="member-actions">
                                <?php if ($canManage): ?>
                                    <?php if (!$isMuted): ?>
                                        <div class="action-icon" title="禁言" onclick="openMuteModal('<?= $member ?>')">
                                            <i class="fas fa-microphone-slash" style="color:#e74c3c"></i>
                                        </div>
                                    <?php else: ?>
                                        <div class="action-icon" title="解除禁言" onclick="unmuteMember('<?= $member ?>')">
                                            <i class="fas fa-microphone" style="color:#2ecc71"></i>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <?php if ($isOwner && $isAdminMember && $member !== $currentUser): ?>
                                    <div class="action-icon" title="取消管理员" onclick="removeAdmin('<?= $member ?>')">
                                        <i class="fas fa-user-minus" style="color:#e74c3c"></i>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($isOwner && !$isAdminMember && $member !== $currentUser && $member !== $currentGroup['creator']): ?>
                                    <div class="action-icon" title="设为管理员" onclick="setAdmin('<?= $member ?>')">
                                        <i class="fas fa-user-plus" style="color:#3498db"></i>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <!-- 管理操作卡片 -->
        <div class="management-card">
            <div class="card-title">
                <i class="fas fa-users-cog"></i> 管理操作
            </div>
            
            <button class="action-btn danger-btn" onclick="openModal('mute-modal')">
                <i class="fas fa-microphone-slash"></i> 禁言成员
            </button>
            
            <button class="action-btn success-btn" onclick="openModal('unmute-modal')">
                <i class="fas fa-microphone"></i> 解除禁言
            </button>
            
            <button class="action-btn" onclick="openModal('admin-modal')">
                <i class="fas fa-user-shield"></i> 设置管理员
            </button>
        </div>
    </div>
    
    <!-- 禁言成员模态框 -->
    <div class="modal" id="mute-modal">
        <div class="modal-content">
            <div class="modal-header">
                <div class="modal-title">禁言成员</div>
                <button class="close-modal" onclick="closeModal('mute-modal')">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form method="POST" id="mute-form">
                <input type="hidden" name="action" value="mute_member">
                <input type="hidden" id="mute-member" name="member">
                
                <div class="modal-body">
                    <div class="form-group">
                        <label class="form-label">禁言时长</label>
                        <select class="form-input" name="duration" required>
                            <option value="60">1小时</option>
                            <option value="1440">1天</option>
                            <option value="10080">1周</option>
                            <option value="43200">1个月</option>
                            <option value="525600">1年</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">禁言原因</label>
                        <input type="text" class="form-input" name="reason" value="违反群规" required>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="modal-btn secondary" onclick="closeModal('mute-modal')">取消</button>
                    <button type="submit" class="modal-btn primary">确认禁言</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 解除禁言模态框 -->
    <div class="modal" id="unmute-modal">
        <div class="modal-content">
            <div class="modal-header">
                <div class="modal-title">解除禁言</div>
                <button class="close-modal" onclick="closeModal('unmute-modal')">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form method="POST" id="unmute-form">
                <input type="hidden" name="action" value="unmute_member">
                <input type="hidden" id="unmute-member" name="member">
                
                <div class="modal-body">
                    <div class="form-group">
                        <label class="form-label">选择被禁言的成员</label>
                        <select class="form-input" name="member" required>
                            <option value="">-- 请选择成员 --</option>
                            <?php foreach ($groupMuteData as $member => $muteInfo): ?>
                                <option value="<?= $member ?>"><?= $member ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="modal-btn secondary" onclick="closeModal('unmute-modal')">取消</button>
                    <button type="submit" class="modal-btn primary">解除禁言</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 设置管理员模态框 -->
    <div class="modal" id="admin-modal">
        <div class="modal-content">
            <div class="modal-header">
                <div class="modal-title">设置管理员</div>
                <button class="close-modal" onclick="closeModal('admin-modal')">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form method="POST" id="admin-form">
                <input type="hidden" name="action" value="set_admin">
                
                <div class="modal-body">
                    <div class="form-group">
                        <label class="form-label">选择成员</label>
                        <select class="form-input" name="member" required>
                            <option value="">-- 请选择成员 --</option>
                            <?php foreach ($members as $member): 
                                // 跳过群主和已有管理员
                                if ($member === $currentGroup['creator'] || 
                                    in_array($member, $currentGroup['admins'])) continue;
                            ?>
                                <option value="<?= $member ?>"><?= $member ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="modal-btn secondary" onclick="closeModal('admin-modal')">取消</button>
                    <button type="submit" class="modal-btn primary">设为管理员</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 加载指示器 -->
    <div class="loading" id="loading">
        <div class="spinner"></div>
        <div>正在处理请求...</div>
    </div>
    
    <script>
        // 打开模态框
        function openModal(modalId) {
            document.getElementById(modalId).classList.add('active');
        }
        
        // 关闭模态框
        function closeModal(modalId) {
            document.getElementById(modalId).classList.remove('active');
        }
        
        // 显示加载指示器
        function showLoading() {
            document.getElementById('loading').classList.add('active');
        }
        
        // 隐藏加载指示器
        function hideLoading() {
            document.getElementById('loading').classList.remove('active');
        }
        
        // 打开禁言模态框
        function openMuteModal(member) {
            document.getElementById('mute-member').value = member;
            openModal('mute-modal');
        }
        
        // 解禁成员
        function unmuteMember(member) {
            if (confirm(`确定要解禁成员 ${member} 吗？`)) {
                showLoading();
                
                const formData = new FormData();
                formData.append('action', 'unmute_member');
                formData.append('member', member);
                
                fetch('', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    hideLoading();
                    location.reload();
                })
                .catch(error => {
                    hideLoading();
                    alert('操作失败: ' + error.message);
                });
            }
        }
        
        // 设置管理员
        function setAdmin(member) {
            if (confirm(`确定要将 ${member} 设置为管理员吗？`)) {
                showLoading();
                
                const formData = new FormData();
                formData.append('action', 'set_admin');
                formData.append('member', member);
                
                fetch('', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    hideLoading();
                    location.reload();
                })
                .catch(error => {
                    hideLoading();
                    alert('操作失败: ' + error.message);
                });
            }
        }
        
        // 取消管理员
        function removeAdmin(member) {
            if (confirm(`确定要取消 ${member} 的管理员权限吗？`)) {
                showLoading();
                
                const formData = new FormData();
                formData.append('action', 'remove_admin');
                formData.append('member', member);
                
                fetch('', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    hideLoading();
                    location.reload();
                })
                .catch(error => {
                    hideLoading();
                    alert('操作失败: ' + error.message);
                });
            }
        }
        
        // 表单提交处理
        document.querySelectorAll('form').forEach(form => {
            form.addEventListener('submit', function(e) {
                showLoading();
            });
        });
    </script>
</body>
</html>